package com.traffic.api.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

public class LoadProperty {
	
	private static String PROP_FILE_PATH = "/properties/";
	
	public  Properties load(String propertyName){
		Properties p = new Properties();   
		  try {   
			   p = loadFromFile(true, propertyName);
		  } catch (Exception e1) {   
		   e1.printStackTrace();   
		  }
		  finally{
			  
		  }
		return p;
	}
	
	/**
	 * load property file(default property file is "/util.properties")
	 * 
	 * @param flag
	 * 
	 */
	private Properties loadFromFile(boolean flag, String _fileName) {
		// logger.debug("load property file is ---" + propertyFile);
		InputStream inStream = null;
		Properties property = new Properties();   
		try {
			try {
				inStream = new FileInputStream(getOuterPropertiesFile(_fileName));
			} catch (FileNotFoundException e) {
				// logger.error(e.getMessage(), e);
				System.out.println("load properties file: " + PROP_FILE_PATH + _fileName);
				inStream = PropertyUtils.class.getResourceAsStream(PROP_FILE_PATH + _fileName);
			}
			if(null == inStream){
				return null;
			}
			property.clear();
			property.load(inStream);

			printAll(property);
		} catch (Exception e) {
			if (flag) {
				loadFromFile(false, _fileName);
			} else {
				e.printStackTrace();
			}
		} finally {
			try {
				if (inStream != null) {
					inStream.close();
				}
			} catch (IOException e) {
			}
		}
		
		return property;
	}
	
	private File getOuterPropertiesFile(String _fileName) {
		File file = new File("");
		File propertiesFile = new File(file.getAbsolutePath() + File.separator + PROP_FILE_PATH + _fileName);
		return propertiesFile;
	}
	
	private static void printAll(Properties property) {
		if (property != null && property.entrySet() != null) {
			Iterator<Entry<Object, Object>> iterator = property.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<Object, Object> one = iterator.next();
				String key = (String) one.getKey();
				String value = (String) one.getValue();
				System.out.println("***PropertiesUtil key:" + key + ", value:" + value);
			}
		}

	}

	public static void main(String[] args) {
		LoadProperty p =new LoadProperty();
		p.load("RongCloud");
	}
	
}
